<template>
  <Header></Header>
  <div class="min-h-[calc(100vh-150px)] py-6">
    <div class="w-full max-w-6xl px-4 mx-auto">
      <div class="text-center mb-6">
        <h1 class="text-4xl font-bold text-gray-900 dark:text-white">留言墙</h1>
        <br/>
        <p class="text-gray-600 dark:text-gray-400">有什么想对我说的，来吧</p>
      </div>
      </div>
      <div class="flex justify-end mb-6">
<button 
  @click="openAddMessageDialog"
  class="bg-pink-500 hover:bg-pink-600 text-white font-medium p-5 rounded-full flex items-center justify-center shadow-lg hover:shadow-xl transition-all duration-300 w-16 h-16">
  <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
  </svg>
</button>
      </div>
      
      <!-- 留言列表容器 -->
      <div class="flex flex-col">
        <!-- 留言列表 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 p-6">
        <div 
            v-for="message in messages" 
            :key="message.id" 
            :style="{ backgroundColor: message.color }"
            class="rounded-lg p-5 text-gray-800 shadow-sm hover:shadow-md transition-shadow duration-300 w-100 max-w-full mx-auto h-70">
          <div class="flex justify-between items-start mb-3">
            <div class="text-sm text-gray-500">{{ (message.createTime) }}</div>
            <br/>
            <div class="text-sm text-gray-500">想对我说的话</div>
          </div>
          <div class="text-base leading-relaxed mb-4 whitespace-pre-wrap break-words">
            {{ message.content }}
            <div v-if="message.content.includes('http')" class="mt-2">
              <a :href="extractUrl(message.content)" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline text-sm">
                {{ extractUrl(message.content) }}
              </a>
            </div>
          </div>
          <br/>
             <br/>
                <br/>
             <br/>
           <div class="mt-auto flex justify-end">
      <div class="text-sm font-medium text-gray-600">{{ message.nickname }}</div>
    </div>
        </div>
        
            <!-- 没有留言时的提示 -->
        <div v-if="messages.length === 0" class="col-span-full text-center py-10">
          <p class="text-gray-500 dark:text-gray-400">暂无留言，快来抢占沙发吧！</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mt-8 flex justify-center">
      <nav aria-label="Page navigation example" v-if="total > 0">
        <ul class="flex items-center justify-center mt-10 mb-10 -space-x-px h-10 text-base">
          <li>
            <a v-if="current > 1" @click="getMessages(current - 1)"
              class="flex items-center justify-center px-4 h-10 ml-0 leading-tight text-gray-500 bg-white border border-gray-300 rounded-l-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
              <span class="sr-only">Previous</span>
              <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 6 10">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                  stroke-width="2" d="M5 1 1 5l4 4" />
              </svg>
            </a>
            <a v-else
              class="cursor-not-allowed flex items-center justify-center px-4 h-10 ml-0 leading-tight text-gray-500 bg-white border border-gray-300 rounded-l-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
              <span class="sr-only">Previous</span>
              <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 6 10">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                  stroke-width="2" d="M5 1 1 5l4 4" />
              </svg>
            </a>
          </li>
          <li v-for="page in pages" :key="page">
            <a @click="getMessages(page)"
              class="flex items-center border-gray-300 justify-center px-4 h-10 leading-tight bg-white border dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
              :class="[page == current ? 'text-blue-600 bg-blue-50 hover:bg-blue-100 hover:text-blue-700' : 'text-gray-500  hover:bg-gray-100 hover:text-gray-700']">
              {{ page }}
            </a>
          </li>
          <li>
            <a v-if="current < pages" @click="getMessages(current + 1)"
              class="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
              <span class="sr-only">Next</span>
              <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 6 10">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                  stroke-width="2" d="m1 9 4-4-4-4" />
              </svg>
            </a>
            <a v-else
              class="cursor-not-allowed flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white">
              <span class="sr-only">Next</span>
              <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 6 10">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                  stroke-width="2" d="m1 9 4-4-4-4" />
              </svg>
            </a>
          </li></ul>
        </nav>
      </div>
    </div>
  </div>

    <!-- 添加留言弹窗 -->
    <div v-if="showAddMessageDialog" class="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm flex items-center justify-center z-50 transition-opacity duration-300">
      <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-500 ease-out scale-100">
        <div class="bg-gradient-to-r from-pink-500 to-purple-600 text-white p-5 rounded-t-xl">
         <div class="text-3xl font-bold text-center text-black">留下言论</div>
        </div>
        <div class="p-6">
        
        <form @submit.prevent="submitMessage">
          <div class="mb-5">
            <label class="block text-gray-700 dark:text-gray-300 text-sm font-medium mb-2" for="nickname">
              昵称
            </label>
            <div class="relative">
              <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                </svg>
              </span>
              <input
                v-model="messageForm.nickname"
                class="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent transition-all duration-200"
                id="nickname"
                type="text"
                placeholder="请输入昵称"
                required
              >
            </div>
          </div>
          
          <div class="mb-5">
            <label class="block text-gray-700 dark:text-gray-300 text-sm font-medium mb-2" for="content">
              留言内容
            </label>
            <div class="relative">
              <span class="absolute top-3 left-3 text-gray-500">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>
                </svg>
              </span>
              <textarea
                v-model="messageForm.content"
                class="w-full pl-10 pr-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-pink-500 focus:border-transparent transition-all duration-200"
                id="content"
                rows="5"
                placeholder="想对我说些什么呢？分享你的想法..."
                required
              ></textarea>
            </div>
          </div>
        
          <div class="mb-6">
            <label class="block text-gray-700 dark:text-gray-300 text-sm font-medium mb-3">
              选择卡片颜色
            </label>
            <div class="flex flex-wrap gap-3">
              <div 
                v-for="color in colors"
                :key="color"
                @click="selectColor(color)"
                :style="{ backgroundColor: color }"
                class="w-12 h-12 rounded-full cursor-pointer shadow-md hover:transform hover:scale-110 transition-all duration-300"
                :class="{ 'ring-4 ring-offset-2 ring-pink-500': messageForm.color === color }">
              </div>
            </div>
          </div>
          
          <div class="flex items-center justify-between pt-4 border-t border-gray-100 dark:border-gray-700">
            <button 
              type="button"
              @click="closeAddMessageDialog"
              class="px-6 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-800 font-medium rounded-lg focus:outline-none focus:ring-2 focus:ring-gray-400 transition-all duration-200">
              取消
            </button>
          <button 
              type="submit"
              class="px-6 py-2.5 bg-blue-100 hover:bg-gray-200 text-gray-800 font-medium rounded-lg focus:outline-none focus:ring-2 focus:ring-gray-400 transition-all duration-200">
              发布留言
            </button>
          </div>
        </form>
        </div>
      </div>
    </div>
</template>

<script setup>
import Header from '@/layouts/components/Header.vue'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addMessage, getMessageList } from '@/api/frontend/message.js'

// 留言数据
const messages = ref([])
const showAddMessageDialog = ref(false)

// 分页相关
const total = ref(0)
const current = ref(1)
const size = ref(9)
const pages = ref(0)

// 颜色选项
const colors = ref([
  '#FFF7E0', '#D1ECF3', '#E4DBDE', '#E9DAF1'
])

// 留言表单
const messageForm = reactive({
  nickname: '',
  content: '',
  color: colors.value[0]
})

// 获取留言列表
const getMessages = async (page = 1) => {
  const params = {
    current: page,
    size: size.value
  }
  try {
    const res = await getMessageList(params)
    if (res && res.success && res.data) {
      // 确保数据结构正确
      messages.value = res.data.records || data.list || []
      total.value = res.data.total || 0
      current.value = res.data.current || 1
      size.value = res.data.size || 9
      pages.value = res.data.pages || Math.ceil(total.value / size.value) || 0
    } else {
      ElMessage.error(res.message || '获取留言列表失败')
    }
  } catch (err) {
    ElMessage.error('获取留言列表失败')
    console.error('获取留言列表时发生错误:', err)
  }
}

// 打开添加留言对话框
const openAddMessageDialog = () => {
  showAddMessageDialog.value = true
}

// 关闭添加留言对话框
const closeAddMessageDialog = () => {
  showAddMessageDialog.value = false
  // 重置表单
  messageForm.nickname = ''
  messageForm.content = ''
  messageForm.color = colors.value[0]
}

// 选择颜色
const selectColor = (color) => {
  messageForm.color = color
}

// // 格式化日期
// const formatDate = (dateString) => {
//   const date = new Date(dateString)
//   const year = date.getFullYear()
//   const month = String(date.getMonth() + 1).padStart(2, '0')
//   const day = String(date.getDate()).padStart(2, '0')
//   const hours = String(date.getHours()).padStart(2, '0')
//   const minutes = String(date.getMinutes()).padStart(2, '0')
//   const seconds = String(date.getSeconds()).padStart(2, '0')
//   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
// }

// 提交留言
const submitMessage = async () => {
  if (!messageForm.nickname || !messageForm.content) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (!messageForm.color) {
    ElMessage.warning('请选择留言颜色')
    return
  }

  try {
    const res = await addMessage(messageForm)

    if (res && res.success) {
      ElMessage.success('留言提交成功，等待审核')
      closeAddMessageDialog()
      getMessages()
    } else {
      ElMessage.error(res.message || '留言提交失败')
    }
  } catch (err) {
    ElMessage.error('留言提交失败')
    console.error('提交留言时发生错误:', err)
  }
}

// 初始化
onMounted(() => {
  getMessages()
})
</script>

<style scoped>
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

  body {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }

  @media (max-width: 768px) {
    .lg\:grid-cols-3 {
      grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
    }
  }

  @media (max-width: 640px) {
    .lg\:grid-cols-3 {
      grid-template-columns: 1fr !important;
    }

    h1 {
      font-size: 2rem !important;
    }
  }

  /* 平滑滚动效果 */
  html {
    scroll-behavior: smooth;
  }

  /* 加载动画 */
  .skeleton {
    animation: skeleton-loading 1.5s linear infinite alternate;
  }

  @keyframes skeleton-loading {
    0% {
      background-color: rgba(255, 255, 255, 0.1);
    }
    100% {
      background-color: rgba(255, 255, 255, 0.2);
    }
  }
</style>